package org.sfgeeq.chapter2.helper;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.sfgeeq.chapter2.util.CollectionUtil;
import org.sfgeeq.chapter2.util.PropsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 使用线程来创建数据库联接
 * 本方法与DatabaseHelper的区别在于，数据库连接请求，是放到线程中进行缓存的，无需从DAO中转递 conn数据库的连接
 * Created by  on 2016/8/25.
 */
public final class DatabaseHelperThreadLocal {
    private static final Logger log= LoggerFactory.getLogger(DatabaseHelperThreadLocal.class);
    private static final ThreadLocal<Connection> CONNECTION_HOLDER;

    private static final QueryRunner QUERY_RUNNER;
    private static final BasicDataSource DATA_SOURCE;

    static {
        CONNECTION_HOLDER=new ThreadLocal<Connection>();
        QUERY_RUNNER=new QueryRunner();
        Properties conf= PropsUtil.loadProps("config.properties");
        String driver=conf.getProperty("jdbc.driver");
        String url=conf.getProperty("jdbc.url");
        String userName=conf.getProperty("jdbc.username");
        String password=conf.getProperty("jdbc.password");
        DATA_SOURCE=new BasicDataSource();
        DATA_SOURCE.setDriverClassName(driver);
        DATA_SOURCE.setUrl(url);
        DATA_SOURCE.setUsername(userName);
        DATA_SOURCE.setPassword(password);
    }


    /**
     * 获取数据库连接
     */
    public static Connection getConnection(){

        Connection conn=CONNECTION_HOLDER.get();//从当前线程中获取数据库连接
        if(conn!=null){
            System.out.println(conn.toString());
        }
        if(conn==null){
            try {
                conn= DATA_SOURCE.getConnection();
            } catch (SQLException e) {
                log.error("get connection failure(获取数据库连接失败)",e);
                throw new RuntimeException(e);
            }finally {
                CONNECTION_HOLDER.set(conn);
            }

        }

        return conn;
    }
    /**
     * 关闭数据库连接
     */
    public static void closeConnection(){
        Connection conn=CONNECTION_HOLDER.get();
        if(conn !=null){
            try {
                conn.close();
                CONNECTION_HOLDER.set(null);
            } catch (SQLException e) {
                log.error("数据库连接关闭失败。",e);
            }
        }
    }



    /**
     * 查询实体列表
     * @param entityClass
     * @param sql           要查询的SQL
     * @param params        查询的入参
     * @param <T>
     * @return
     */
    public static <T> List<T> queryEntityList(Class<T> entityClass,String sql,Object... params){
        List<T> entityList;
        try {
            Connection conn=getConnection();
            entityList=QUERY_RUNNER.query(conn,sql,new BeanListHandler<T>(entityClass),params);
        } catch (Exception e) {
            log.error("execute query failure(执行查询出错)",e);
            throw new RuntimeException(e);
        }finally {
            closeConnection();
        }
        return entityList;
    }

    /**
     * 查询实体列表
     * @param entityClass
     * @param sql           要查询的SQL
     * @param params        查询的入参
     * @param <T>
     * @return
     */
    public static <T> T queryEntity(Class<T> entityClass,String sql,Object... params){
        T entity;
        try {
            Connection conn=getConnection();
            entity=QUERY_RUNNER.query(conn,sql,new BeanHandler<T>(entityClass),params);
        } catch (Exception e) {
            log.error("execute query failure(执行查询出错)",e);
            throw new RuntimeException(e);
        }finally {
            closeConnection();
        }
        return entity;
    }

    /**
     * QUERY_RUNNER.query(conn,sql,new BeanHandler<T>(entityClass),params);
     * DBUtils 为我们提供了很多类似 Handler方法有：
     * BeanHandler      返回单个bean对象
     * BeanListHandler      返回List对象
     * BeanMAPHandler      返回map对象
     * ArrayHandler      返回OBJECT[] 数据对象
     * ArrayListHandler     返回LIST对象
     * MapListHandler       返回LIST对象
     * MapHandler
     * ScalarHandler    返回某列值
     * ColumnListHandler    返回某列的值列表
     * KeyedHandler         返回Map对象，需要指定列名
     */


    /**
     *查询的工具类
     * @param sql
     * @param params
     * @return
     */
    public static List<Map<String,Object>> executeQuery(String sql,Object... params){
        List<Map<String,Object>> result;
        try {
            Connection conn=getConnection();
            result=QUERY_RUNNER.query(conn,sql,new MapListHandler(),params);
        } catch (SQLException e) {
            log.error("执行查询出错",e);
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 执行更新语句(有：update,insert,delete) 等set类的SQL
     * @param sql
     * @param params
     * @return
     */
    public static int executeUpdate(String sql,Object... params){
        int rows=0;
        Connection conn=getConnection();
        try {
            rows=QUERY_RUNNER.update(conn, sql, params);
        } catch (SQLException e) {
            log.error("执行修改操作：\n\r"+sql+"失败。",e);
            throw new RuntimeException(e);
        }
        return rows;
    }

    /**
     * 插入实体
     * @param entityClass
     * @param fieldMap
     * @param <T>
     * @return
     */
    public static <T> boolean addEntity(Class<T> entityClass,Map<String,Object> fieldMap){
        if(CollectionUtil.isEmpty(fieldMap)){//先判断参数是否为空
            log.error("can not insert entity:fieldMap is empty（新增SQL，你入参为空，所以新增失败）");
            return false;
        }
        String sql ="INSERT INTO "+getTableName(entityClass);
        StringBuffer columns =new StringBuffer("(");
        StringBuffer values =new StringBuffer("(");
        for(String fieldName:fieldMap.keySet()){
            columns.append(fieldName).append(", ");
            values.append("?, ");
        }
        columns.replace(columns.lastIndexOf(", "),columns.length(),")");
        values.replace(values.lastIndexOf(", "),values.length(),")");
        sql+=columns+" VALUES "+values;
        Object[] params=fieldMap.values().toArray();
        return executeUpdate(sql,params)==1;
    }

    /**
     * 更新实体
     * @param entityClass
     * @param id
     * @param fieldMap
     * @param <T>
     * @return
     */
    public static <T> boolean updateEntity(Class<T> entityClass,long id,Map<String,Object> fieldMap){
        if(CollectionUtil.isEmpty(fieldMap)){//先判断参数是否为空
            log.error("can not update entity:fieldMap is empty（修改SQL，你入参为空，所以修改失败）");
            return false;
        }
        String sql =" UPDATE  "+getTableName(entityClass)+" SET ";
        StringBuffer columns =new StringBuffer();
        for(String fieldName:fieldMap.keySet()){
            columns.append(fieldName).append("=?, ");
        }
        sql+=columns.substring(0,columns.lastIndexOf(", "))+" WHERE ID=?";
        List<Object> paramList=new ArrayList<Object>();
        paramList.addAll(fieldMap.values());
        paramList.add(id);
        Object[] params=fieldMap.values().toArray();
        return executeUpdate(sql,params)==1;
    }

    /**
     * 删除实体
     * @param entityClass
     * @param id
     * @param <T>
     * @return
     */
    public static <T> boolean delEntity(Class<T> entityClass,long id){
        String sql="DELETE FROM "+getTableName(entityClass)+" WHERE ID=? ";
        return executeUpdate(sql,id)==1;
    }

    private static String getTableName(Class<?> entityClass){
        return entityClass.getSimpleName();
    }

    /**
     * 执行SQL文件
     * @param filePath
     */
    public static void executeSqlFile(String filePath){
        InputStream is=Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);//读取出文件流
        BufferedReader reader=new BufferedReader(new InputStreamReader(is));
        try {
            String sql;
            while ((sql=reader.readLine()) !=null){
                executeUpdate(sql);
            }
        } catch (IOException e) {
           log.error("执行SQL文件出错");
            throw new RuntimeException(e);
        }



    }
}